<?php

namespace app\api\controller;

use app\api\validate\Admin;
use app\common\model\AdminModel;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\captcha\Captcha;
use think\Request;

class Login extends Cross
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index(Request $request)
    {

        //
        $data =$request->param();

        //验证
        $validate = new Admin();
        $result = $validate->check($data);
        if(!$result){
            return json(['code'=>0,'message'=>$validate->getError()]);
        }
//        $captcha = new Captcha();
//        $captcha->codeSet = '0123456789';
//        if(!$captcha->check($data['captcha'])){
//            return json(['code'=>0,'message'=>'验证码错误']);
//        }
        $db = new AdminModel();
        $info = $db->where('username',$data['username'])->find();
        if (!$info){
            return json(['code'=>0,'message'=>'未找到用户']);
        }
        if ($info['fail_cnt']>=100){
            return json(['code'=>0,'message'=>'100+,不可登录']);
        }

        if (empty($info) || $info['password'] != md5($data['password'])){
            //记录失败次数
            $db->where('id',$info['id'])->setInc('fail_cnt');

            return json(['code'=>0,'message'=>'密码错误']);
        }

        $jwt = new JWT();
        $key = 'api';
        $payload = [
            'iss' => 'http://rb.io',
            'aud' => 'http://rb.io',
//            'iat' => time(),
//            'nbf' => time() + 60 * 60,
            'iat' => time(),
            'nbf' => 1357000000,
            'uid' => $info['id']
        ];
        $jwt = JWT::encode($payload, $key, 'HS256');
        $token = $jwt;
        return json(['code'=>1,'msg'=>'登录成功','token'=>$token]);
//        $decoded = JWT::decode($jwt,  new Key($key, 'HS256'));
//        print_r($decoded);
        echo '账号密码验证通过';





    }
    public function loginxxx(Request $request){
        $captcha = new Captcha();
        $captcha->length   = 4;
        $captcha->codeSet = '0123456789';
        return $captcha->entry();
    }

}
